package com.zx.controller;

import com.zx.bean.Message;
import com.zx.exception.DuplicateCodeException;
import com.zx.mvc.ResponseBody;
import com.zx.service.AdminService;
import com.zx.util.JsonUtil;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Random;


public class AdminController {
    @ResponseBody("/test/admin/login.do")
    public String login(HttpServletRequest request,HttpServletResponse response){
        //1 接参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        //2调用service传参数 ,并获取结果
        boolean result = AdminService.login(username, password);

        //3 根据结果 返回数据给ajax客户端
        Message msg=null;
        if (result) {
            msg=new Message(0,"true") ;
            //登陆时间更新  和ip更新
            Date date=new Date();
            String ip=request.getRemoteAddr();//拿到IP
            AdminService.updateLoginTimeAndIp(username,date,ip);
            request.getSession().setAttribute("adminUserName",username);
        }else{
            msg=new Message(-1,"false" );
        }


        //将数据转化为JSON 并返回
        String json = JsonUtil.toJson(msg);

        return json;
    }
    /**
    * @Author: 吴澳
    * @Description:注册业务逻辑
    * @Param:* @param null
    * @Date: 2022/3/4
    */
    @ResponseBody("/test/admin/register.do")
    public String register(HttpServletRequest request,HttpServletResponse response) throws DuplicateCodeException {
        String username=request.getParameter("name");
        String password=request.getParameter("password");
        String address=request.getParameter("address");
        String coding=request.getParameter("coding");
        String phonenumber=request.getParameter("phonenumber");
        boolean result=AdminService.register(username,password,address,phonenumber,coding);
        Message msg= null;
        if (result){
            msg=new Message(0,"true");
        }else{
            msg=new Message(-1,"false");
        }
        //将数据转化为json并且返回
        String json=JsonUtil.toJson(msg);

        return json;
    }
    public String  getRandomIp(){
        Random random=new Random();
        int ip=random.nextInt(10000);
        String ipStr=ip+"";
        return ipStr;
    }
}
